/*	
	
	Copyright (c) 2007-2009 Ryan Christiansen
	
	This software is provided 'as-is', without any express or implied
	warranty. In no event will the authors be held liable for any damages
	arising from the use of this software.
	
	Permission is granted to anyone to use this software for any purpose,
	including commercial applications, and to alter it and redistribute it
	freely, subject to the following restrictions:
	
	1. The origin of this software must not be misrepresented; you must not
	claim that you wrote the original software. If you use this software
	in a product, an acknowledgment in the product documentation would be
	appreciated but is not required.
	
	2. Altered source versions must be plainly marked as such, and must not be
	misrepresented as being the original software.
	
	3. This notice may not be removed or altered from any source
	distribution.
	
*/
package funit.core
{
	import flash.utils.getTimer;
	
	import funit.core.builders.TestFixtureBuilder;
	import funit.core.events.AsyncEvent;
	import funit.core.events.SchedulerCompleteEvent;
	import funit.core.events.SchedulerEvent;
	import funit.errors.AssertionError;
	import funit.errors.IgnoreError;
	
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
	import sv.errors.NotImplementedError;
	import sv.reflection.MethodInfo;
	import sv.reflection.Type;
	import sv.utils.ErrorUtil;
	
	public class TestSuite extends TestBase
	{
		private var _tests:ArrayCollection = new ArrayCollection();
		
		private var _fixtureSetUp:MethodInfo = null;
		private var _fixtureTearDown:MethodInfo = null;
		
		
		/**
		 * @param fixtureType
		 */
		public function TestSuite( fixtureType:Type = null )
		{
			super(fixtureType);
		}
		
		
		/**
		 * @param fixture
		 */
		public function add( fixture:Object ) : void
		{
			if (fixture is ITest)
			{
				addTest( ITest(fixture) );
			}
			else
			{
				var test:TestSuite = TestFixtureBuilder.buildFrom(fixture);
				
				if (test != null)
				{
					addTest(test);
				}
			}
		}
		
		/**
		 * @param test
		 */
		public function addTest( test:ITest ) : void
		{
			_tests.addItem(test);
		}
		
		/**
		 * @param definition
		 */
		public function addDefinition( definition:Class ) : void
		{
			add(definition);
		}
		
		/**
		 * @param type
		 */
		public function addType( type:Type ) : void
		{
			add(type);
		}
		
		/**
		 * 
		 */
		public function sort() : void
		{
			throw new NotImplementedError();
		}
		
		/**
		 * @param listener
		 */
		override public function run( listener:ITestListener ) : void
		{
			var suiteResult:TestResult = createTestResult();
			
			listener.suiteStarted( this.testName );
			suiteResult.startTime = getTimer();
			
			switch (this.runState)
			{
				case RunState.Runnable:
				case RunState.Explicit:
					suiteResult.runState = RunState.Executed;
					runOneTimeSetUp(suiteResult);
					if ( suiteResult.isFailure )
					{
						markTestsFailed(this.tests, suiteResult, listener);
						suiteFinished(suiteResult, listener);
					}
					else
					{
						runAllTests(suiteResult, listener);
					}
					break;
				
				case RunState.Skipped:
					suiteResult.skip(this.ignoreReason);
					markTestsNotRun(this.tests, RunState.Skipped, this.ignoreReason, suiteResult, listener);
					suiteFinished(suiteResult, listener);
					break;
				
				case RunState.Ignored:
				case RunState.NotRunnable:
				default:
					suiteResult.ignore(this.ignoreReason);
					markTestsNotRun(this.tests, RunState.Ignored, this.ignoreReason, suiteResult, listener);
					suiteFinished(suiteResult, listener);
					break;
			}
		}
		
		/**
		 * @param suiteResult
		 * @param listener
		 */
		private function suiteFinished( suiteResult:TestResult, listener:ITestListener ) : void
		{
			var stopTime:Number = getTimer();
			suiteResult.time =  stopTime - suiteResult.startTime;
			
			listener.suiteFinished(suiteResult);
			
			finishTest(suiteResult);
		}
		
		/**
		 * @param suiteResult
		 * @param listener
		 */
		private function runAllTests( suiteResult:TestResult, listener:ITestListener ) : void
		{
			var scheduler:TestScheduler = new TestScheduler(this.tests);
			
			scheduler.addEventListener(
				SchedulerEvent.SCHEDULE,
				function( event:SchedulerEvent ) : void
				{
					runTest(event.test, scheduler, suiteResult, listener);
				}
			);
			
			scheduler.addEventListener(
				SchedulerCompleteEvent.COMPLETE,
				function( event:SchedulerCompleteEvent ) : void
				{	
					runOneTimeTearDown(suiteResult);
					suiteFinished(suiteResult, listener);
				}
			);
			
			scheduler.scheduleNextTest();
		}
		
		/**
		 * @param test
		 * @param scheduler
		 * @param suiteResult
		 * @param listener
		 */
		private function runTest( test:ITest, scheduler:TestScheduler, suiteResult:TestResult, listener:ITestListener ) : void
		{
			var saveRunState:RunState = test.runState;
			var saveFixture:Object = test.fixture;
			
			test.addEventListener(
				AsyncEvent.FINISH,
				function( event:AsyncEvent ) : void
				{
					test.removeEventListener(AsyncEvent.FINISH, arguments.callee);
					
					suiteResult.addResult(event.result);
					
					// Restore the initial test state. This allows
					// support for re-running the test instance.
					if (saveRunState != test.runState)
					{
						test.runState = saveRunState;
						test.ignoreReason = null;
					}
					
					if (saveFixture != test.fixture)
					{
						test.fixture = saveFixture;
					}
					
					scheduler.scheduleNextTest();
				}
			);
			
			if (test.runState == RunState.Runnable && this.runState != RunState.Runnable && this.runState != RunState.Explicit )
			{
				test.runState = this.runState;
				test.ignoreReason = this.ignoreReason;
			}
			
			if (test.fixture == null)
			{
				test.fixture = this.fixture;
			}
			
			test.run(listener);
		}
		
		/**
		 * @param suiteResult
		 */
		protected function runOneTimeSetUp( suiteResult:TestResult ) : void
		{
			if (fixtureType != null)
			{
				try
				{
					if (this.fixture == null)
					{
						createUserFixture();
					}
					
					if (this.fixtureSetUp != null)
					{
						this.fixtureSetUp.invoke(this.fixture);
					}
				}
				catch (e:Error)
				{
					if (e is IgnoreError)
					{
						this.runState = RunState.Ignored;
						suiteResult.ignore(e.message);
						suiteResult.stackTrace = ErrorUtil.getStackTrace(e);
						this.ignoreReason = e.message;
					}
					else if (e is AssertionError)
					{
						suiteResult.failure(e.message, ErrorUtil.getStackTrace(e), FailureSite.SetUp);
					}
					else
					{
						suiteResult.error(e, FailureSite.SetUp);
					}
				}
			}
		}
		
		/**
		 * @param suiteResult
		 */
		protected function runOneTimeTearDown( suiteResult:TestResult ) : void
		{
			if (this.fixture != null)
			{
				try
				{
					if (this.fixtureTearDown != null)
					{
						this.fixtureTearDown.invoke(this.fixture);
					}
				}
				catch (e:Error)
				{
					if (e is AssertionError)
					{
						suiteResult.failure(e.message, ErrorUtil.getStackTrace(e), FailureSite.TearDown);
					}
					else
					{
						suiteResult.error(e, FailureSite.TearDown);
					}
				}
				finally
				{
					this.fixture = null;
				}
			}
		}
		
		/**
		 * 
		 */
		protected function createUserFixture() : void
		{
			this.fixture = fixtureType.createInstance();
		}
		
		/**
		 * @param tests
		 * @param runState
		 * @param ignoreReason
		 * @param suiteResult
		 * @param listener
		 */
		private function markTestsNotRun( tests:Array, runState:RunState, ignoreReason:String, suiteResult:TestResult, listener:ITestListener ) : void
		{
			for each ( var test:ITest in tests )
			{
				markTestNotRun(test, runState, ignoreReason, suiteResult, listener);
			}
		}
		
		/**
		 * @param test
		 * @param runState
		 * @param ignoreReason
		 * @param suiteResult
		 * @param listener
		 */
		private function markTestNotRun( test:ITest, runState:RunState, ignoreReason:String, suiteResult:TestResult, listener:ITestListener ) : void
		{
			var result:TestResult;
			
			if (test is TestSuite)
			{
				listener.suiteStarted(test.testName);
				result = new TestResult(test, test.testName.fullName);
				result.notRun(runState, ignoreReason, null);
				markTestsNotRun(test.tests, runState, ignoreReason, suiteResult, listener);
				suiteResult.addResult(result);
				listener.suiteFinished(result);
			}
			else
			{
				listener.testStarted(test.testName);
				result = new TestResult(test, test.testName.fullName);
				result.notRun(runState, ignoreReason, null);
				suiteResult.addResult(result);
				listener.testFinished(result);
			}
		}
		
		/**
		 * @param tests
		 * @param suiteResult
		 * @param listener
		 */
		private function markTestsFailed( tests:Array, suiteResult:TestResult, listener:ITestListener ) : void
		{
			for each ( var test:ITest in tests )
			{
				markTestFailed(test, suiteResult, listener);
			}
		}
		
		/**
		 * @param test
		 * @param suiteResult
		 * @param listener
		 */
		private function markTestFailed( test:ITest, suiteResult:TestResult, listener:ITestListener ) : void
		{
			var result:TestResult;
			var message:String;
			
			if (test is TestSuite)
			{
				listener.suiteStarted(test.testName);
				result = new TestResult(test, test.testName.fullName);
				message = StringUtil.substitute( "Parent SetUp failed in {0}", this.fixtureType.name );
				result.failure(message, null, FailureSite.Parent);
				markTestsFailed(test.tests, suiteResult, listener);
				suiteResult.addResult(result);
				listener.suiteFinished(result);
			}
			else
			{
				listener.testStarted(test.testName);
				result = new TestResult(test, test.testName.fullName);
				message = StringUtil.substitute( "TestFixtureSetUp failed in {0}", this.fixtureType.name );
				result.failure(message, null, FailureSite.Parent);
				suiteResult.addResult(result);
				listener.testFinished(result);
			}
		}
		
		
		/**
		 * 
		 */
		public function get fixtureSetUp() : MethodInfo
		{
			return _fixtureSetUp;
		}
		
		public function set fixtureSetUp( value:MethodInfo ) : void
		{
			_fixtureSetUp = value;
		}
		
		
		/**
		 * 
		 */
		public function get fixtureTearDown() : MethodInfo
		{
			return _fixtureTearDown;
		}
		
		public function set fixtureTearDown( value:MethodInfo ) : void
		{
			_fixtureTearDown = value;
		}
		
		
		/**
		 * 
		 */
		override public function get testType() : String
		{
			return "Test Suite";
		}
		
		
		/**
		 * 
		 */
		override public function get isSuite() : Boolean
		{
			return true;
		}
		
		
		/**
		 * 
		 */
		override public function get testCount() : int
		{
			var count:int = 0;
			
			for each ( var test:ITest in _tests )
			{
				count += test.testCount;
			}
			
			return count;
		}
		
		
		/**
		 * 
		 */
		override public function get tests() : Array
		{
			return _tests.toArray();
		}
		
	}
	
}
